package com.bawei.day11_contentprovider;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RequiresApi;

public class SongsUtils {
    private Context context;
    //单例
    private SongsUtils(Context context){
        this.context = context;
    }
    private static SongsUtils songsUtils;
    public  synchronized   static SongsUtils getInstance(Context context){
        if(songsUtils == null){
            songsUtils = new SongsUtils(context);
        }
        return songsUtils;
    }
    public List<SongBean> getSongs(){
        ArrayList<SongBean> songBeans = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
        if(cursor != null){
            while (cursor.moveToNext()){
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String album_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                //根据id获得专辑图片地址
                Uri uri = Uri.parse("content://media/external/audio/albums/" + album_id);
                Cursor cursor1 = contentResolver.query(uri, null, null, null, null);
                if(cursor1 != null){
                    while (cursor1.moveToNext()){
                        String album = cursor1.getString(cursor1.getColumnIndex("album_art"));
                        songBeans.add(new SongBean(name,singer,data,album));
                    }
                }

            }
        }
        return songBeans;




    }



}
